<template>
  <div>
    <form action="/">
      <van-search
        v-model.trim="keywords"
        show-action
        placeholder="请输入搜索关键词"
        class="search-inp"
        @search="onSearch"
        @cancel="onCancel"
        @focus="isShowResult = false"
        background="#3496f9"
      />
    </form>
    <!-- 搜索历史 -->
    <!-- 搜索建议 -->
    <!-- 搜索结果 -->
    <!-- 使用动态主键 -->
    <component
      :keywords="keywords"
      @updata-keywords="onSearch"
      :is="componentName"
    ></component>
  </div>
</template>

<script>
import searchHistory from './components/SearchHistory.vue'
import SearchSuggestions from './components/SearchSuggestions.vue'
import SearchResult from './components/SearchResult.vue'
import { mapMutations, mapState } from 'vuex'
export default {
  name: 'Search',
  components: {
    searchHistory,
    SearchSuggestions,
    SearchResult
  },
  props: {},
  data() {
    return {
      //  绑定value值
      keywords: '',
      // 是否展示搜索结果
      isShowResult: false
    }
  },
  computed: {
    ...mapState(['historys']),
    componentName() {
      //  判断 当keywords去除空格后没有内容显示 'searchHistory'
      if (this.keywords === '') {
        return 'searchHistory'
      }
      //  如果触发搜索事件 则展示搜索结果
      if (this.isShowResult) {
        return 'SearchResult'
      }
      //  前两者都不满足情况下触发搜索建议
      return 'SearchSuggestions'
    }
  },
  watch: {},
  created() {},
  methods: {
    ...mapMutations(['SET_HISTORYS']),
    onSearch(val) {
      // 1.让keywords的值大于点击的搜索建议的值
      this.keywords = val
      // 2. 存储历史搜索级记录
      let newHistory = [this.keywords, ...this.historys]
      // 3. 数组去重
      newHistory = [...new Set(newHistory)]
      this.SET_HISTORYS(newHistory)
      // 4.触发搜索事件 ，讲展示内容变成搜索结果
      this.isShowResult = true
    },
    onCancel() {
      this.$router.push('/')
    }
  }
}
</script>

<style scoped lang="less">
.search-inp {
  .van-search__action {
    color: #fff;
  }
}
</style>
